const ssh = require('./ssh.js')

/**
 * 服务器上安装 npm 包
 * @param {Object} packageName npm 包名称
 */
async function installPackage(packageName) {
    let forever = await ssh.execute('npm ls ' + packageName + ' -g')
    if (forever == null || forever == '') {
        await ssh.execute('npm install --prefix /usr/local/lib ' + forever + ' -g')
    }
}

/**
 * 将此命令注册为开机启动
 * @param {Object} commondName 命令名称
 */
async function startupCommand(commondName) {
    await ssh.execute('echo ' + commondName + ' >> /etc/rc.d/rc.local')
    await ssh.execute('chmod +x /etc/rc.d/rc.local')
}

/**
 * 将 forever 安装到服务器
 */
async function installForever() {
    let forever = await ssh.execute('npm ls forever -g')
    if (forever == null || forever == '') {
        await ssh.execute('npm install --prefix /usr/local/lib forever -g')
    }
}

/**
 * 将 server 注册为开机启动
 */
async function startupForever() {
    let has = await checkedForever()
    if (!has) {
        let script = "'./usr/local/lib/node_modules/forever/bin/forever start -w /root/server.js'"
        await ssh.execute('echo ' + script + ' >> /etc/rc.d/rc.local')
        await ssh.execute('chmod +x /etc/rc.d/rc.local')
    }
}

/**
 * 将 server 注册为开机启动
 */
async function checkedForever() {
    let content = await ssh.execute('cat /etc/rc.d/rc.local')
    let commandList = content.split('\n')
    let command = commandList.find(
        o =>
            o.indexOf(
                './usr/local/lib/node_modules/forever/bin/forever start -w /root/server.js'
            ) != -1
    )
    return command != null
}

module.exports = {
    installPackage,
    startupCommand,
    startupForever,
    installForever
}
